import os
import configparser
import json

import requests

BASE_DIR = os.path.dirname(os.path.abspath(__file__))


def init_settings():
    file_path = os.path.join(BASE_DIR, 'setting.ini')
    config = configparser.ConfigParser()
    config.read(file_path, encoding='utf-8')
    result = {}
    sec_list = config.sections()
    for sec in sec_list:
        result[sec] = {}
        for k, v in config.items(sec):
            result[sec][k] = v
    return result


def run():
    settings = init_settings()
    print(settings)

    # 1.下载页面中返回的数据
    url = settings['zhihu']['url']
    res = requests.get(
        url=url,
        headers={
            "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36"
        }
    )
    res.encoding = 'utf-8'

    data_dict = json.loads(res.text)
    print(data_dict)

    file_name = settings['zhihu']['file']
    abs_file_path = os.path.join(BASE_DIR, file_name)
    with open(abs_file_path, mode='a', encoding='utf-8') as f:
        for item in data_dict['data']:
            name = item['author']['name']
            content = item['content']
            f.write(content + "\n")


if __name__ == '__main__':
    run()
